#include <fcntl.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <string>
#include <algorithm>

#include <sw/redis++/redis++.h>

using namespace std;
using namespace sw::redis;

const string REDIS_URL      = "tcp://172.17.0.3"; // 存储网络拓扑信息的数据库
const string REDIS_PASSWD   = "uEstC318.#"; // 数据库
const string BANDWIDTH_KEY  = "QUEUE-BANDWIDTH";


/*
 * buf: "s1101-s1201-1-tx,123456;s1101-s1102-1-tx,123456;"
 */
void parse_buf(char *buf, int len, unordered_map<string, string>& ump)
{
    string tmp, field;
    int idx;
    for (int i = 0; i < len; i++) {
        if (buf[i] == ';') {
            idx = tmp.find(',');
            field = tmp.substr(0, idx);
            field.erase(remove(field.begin(), field.end(), 's'), field.end());
            ump[field] = tmp.substr(idx+1);
            tmp = "";
        } else
            tmp += buf[i];
    }
}

int main()
{
    Redis redis_cli(REDIS_URL);
    redis_cli.auth(REDIS_PASSWD);

    const char* pathname = "/tmp/ovs-ats-fifo-ovs-netdev";
    int fd = open(pathname, O_RDONLY);

    char buf[2000] = "";
    int bytes = 0;
    unordered_map<string, string> ump;

    while (1) {
        buf[0] = '\0';
        bytes = read(fd, buf, 2000);
        if (bytes == 0)
            break;
        if (bytes < 0)
            continue;
        buf[bytes] = '\0';
        printf("read from fifo: %s\n", buf);

        parse_buf(buf, bytes, ump);
        redis_cli.hmset(BANDWIDTH_KEY, ump.begin(), ump.end());

        ump.clear();
    }

    return 0;
}
